package com.example.app02

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.MenuItem
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class Activity3 : AppCompatActivity() {
    private val REQUEST_CAMERA = 100 // 相机权限请求码
    private var photoUri: Uri? = null // 改为可空类型，解决赋值错误

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity3)
        title = getString(R.string.activity3_title)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 绑定拍照按钮点击事件
        findViewById<Button>(R.id.btnTakePhoto).setOnClickListener {
            Log.d("Activity3", "拍照按钮被点击")
            checkCameraPermission()
        }
    }

    // 检查相机权限
    private fun checkCameraPermission() {
        Log.d("Activity3", "开始检查相机权限")
        if (ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            Log.d("Activity3", "未获取相机权限，发起请求")
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.CAMERA),
                REQUEST_CAMERA
            )
        } else {
            Log.d("Activity3", "已获取相机权限，准备拍照")
            takePhoto()
        }
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("Activity3", "用户授予相机权限")
                takePhoto()
            } else {
                Log.d("Activity3", "用户拒绝相机权限")
                Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 启动相机拍照
    private fun takePhoto() {
        Log.d("Activity3", "进入takePhoto方法")

        // 1. 创建相机Intent
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 检查是否有应用可处理相机请求
        if (takePictureIntent.resolveActivity(packageManager) == null) {
            Log.e("Activity3", "无可用相机应用")
            Toast.makeText(this, "未找到相机应用", Toast.LENGTH_SHORT).show()
            return
        }

        // 2. 创建存储照片的文件
        val photoFile: File? = try {
            createImageFile()
        } catch (e: IOException) {
            Log.e("Activity3", "创建照片文件失败：${e.message}")
            Toast.makeText(this, "创建照片文件失败", Toast.LENGTH_SHORT).show()
            return
        }

        // 3. 通过FileProvider生成Uri
        photoFile?.let { file ->
            try {
                // 生成Uri并赋值（可空类型兼容）
                photoUri = FileProvider.getUriForFile(
                    this,
                    "${packageName}.fileprovider", // 与Manifest中配置一致
                    file
                )
                Log.d("Activity3", "生成照片Uri：$photoUri")
            } catch (e: Exception) {
                Log.e("Activity3", "生成Uri失败：${e.message}")
                Toast.makeText(this, "生成Uri失败", Toast.LENGTH_SHORT).show()
                photoUri = null // 失败时显式设为null
                return
            }

            // 4. 授予Uri临时访问权限
            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            // 设置照片存储路径
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)

            // 5. 启动相机
            try {
                startActivityForResult(takePictureIntent, 101) // 101为拍照请求码
                Log.d("Activity3", "相机已启动")
            } catch (e: Exception) {
                Log.e("Activity3", "启动相机失败：${e.message}")
                Toast.makeText(this, "启动相机失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 创建临时照片文件
    @Throws(IOException::class)
    private fun createImageFile(): File {
        // 生成唯一文件名
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
        val fileName = "JPEG_${timeStamp}_"
        // 获取应用私有照片目录
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            ?: throw IOException("存储目录不可用")
        // 确保目录存在
        if (!storageDir.exists()) {
            storageDir.mkdirs()
        }
        // 创建临时文件
        return File.createTempFile(fileName, ".jpg", storageDir).apply {
            Log.d("Activity3", "照片文件路径：${absolutePath}")
        }
    }

    // 处理拍照结果，返回Uri给MainActivity
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            Log.d("Activity3", "拍照成功，准备返回Uri")
            // 1. 避免用data作为Intent变量名，改为intent
            val intent = Intent()
            // 2. 明确给intent的data属性赋值
            intent.data = photoUri
            // 3. 返回结果
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
    }

    // ActionBar返回按钮事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}